package com.hudongwx.godoffood.fragment.Adapter;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.activity.home_activity.TitleWebActivity;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.List;

/**
 * Created by hudongwx on 16-11-5.
 */
public class MyViewpagerAdapter extends PagerAdapter {
    List<ImageView> imgData;
    JSONArray data;
    Activity activity;

    ImgItemOnclickListener listener;

    public MyViewpagerAdapter(JSONArray data,List<ImageView> imgData,Activity activity) {
        this.data = data;
        this.imgData = imgData;
        this.activity = activity;
        listener = new ImgItemOnclickListener();
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Log.i("MyViewpagerAdapter", "instantiateItem: "+imgData.size());
        View view = LayoutInflater.from(activity).inflate(R.layout.home_title_view_page, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.view_pager_img);
        //对ViewPager页号求模取出View列表中要显示的项
        position %=imgData.size();
        if (position<0){
            position = position+imgData.size();
        }
        imageView = imgData.get(position);
        //如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
        ViewParent vp = imageView.getParent();
        if (vp!=null){
            ViewGroup parent = (ViewGroup) vp;
            parent.removeView(imageView);
        }
        container.addView(imageView);

        try {
            //将图片对应的网页链接传递过去
            imageView.setTag(data.getJSONObject(position).getString("PageUrl"));
            //设置点击事件
            imageView.setOnClickListener(listener);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//        super.destroyItem(container, position, object);
    }

    class ImgItemOnclickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(activity, TitleWebActivity.class);
            intent.putExtra("url",v.getTag()+"");
            activity.startActivity(intent);
        }
    }
}
